package com.cmccsi.utils;

import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;
import java.security.MessageDigest;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;
import org.apache.xmlbeans.impl.util.Base64;

public class SecurityUtil {

	/*
	 * 
	 */
	public String encrypt_des_ecb(String strData, String strKey)
			throws Exception {
		byte[] key = strToToHexByte(strData).getBytes(GetCharSet());
		byte[] plainText = strKey.getBytes(GetCharSet());

		SecretKey secretKey = new SecretKeySpec(key, "DES"); // encrypt
		Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, secretKey);
		byte[] encryptedData = cipher.doFinal(plainText);
		// System.out.println("encrypt_des_ecb: " +
		// Hex.decodeHex(encryptedData));

		String encryptedText = new String(encryptedData, "UTF-8");	
		
		String encryptedBase64Text = new String(Base64.encode(encryptedText.getBytes(GetCharSet())), "UTF-8");

		return encryptedBase64Text;
	}

	private Charset GetCharSet()

	{
		return Charset.forName("UTF-8");
	}
	
	/*
	 * 
	 */
	public String decrypt_des_ecb(String decryptData, String decryptKey)
			throws Exception {
		byte[] key = strToToHexByte(decryptKey).getBytes(GetCharSet());
		byte[] decryptByte =Base64.decode(decryptData.getBytes(GetCharSet()));

		SecretKey secretKey = new SecretKeySpec(key, "DES"); // encrypt
		Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		// System.out.println("encrypt_des_ecb: " +
		// Hex.decodeHex(encryptedData));
		// decrypt
		cipher.init(Cipher.DECRYPT_MODE, secretKey);
		byte[] decryptPlainByte = cipher.doFinal(decryptByte);

		String decryptPlainText = new String(decryptPlainByte, "UTF-8");

		return decryptPlainText;
	}

	public String strToToHexByte(String bytes) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length() / 2);
		
		String hexString = "0123456789ABCDEF";
		for (int i = 0; i < bytes.length(); i += 2)
			baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString.indexOf(bytes.charAt(i + 1))));
		return new String(baos.toByteArray());
	}
	
	public  String MD5(String s) {  
		  char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','a', 'b', 'c', 'd', 'e', 'f' };  
		  try {  
		   byte[] strTemp = s.getBytes();  
		   MessageDigest mdTemp = MessageDigest.getInstance("MD5");  
		   mdTemp.update(strTemp);  
		   byte[] md = mdTemp.digest();  
		   int j = md.length;  
		   char str[] = new char[j * 2];  
		   int k = 0;  
		   for (int i = 0; i < j; i++) {  
		    byte byte0 = md[i];  
		    str[k++] = hexDigits[byte0 >>> 4 & 0xf];  
		    str[k++] = hexDigits[byte0 & 0xf];  
		   }  
		   return new String(str);  
		  } catch (Exception e) {  
		   return null;  
		  }  
		 }  
}
